// 全局变量
let machineData = [];
let pendingPlanData = [];
let refreshInterval;
const REFRESH_INTERVAL = 30000; // 30秒

// 疵点类型映射
const FLAW_TYPE_MAP = {
    0: '停车位',
    1: '横条',
    2: '断头',
    3: '长断头',
    4: '油污',
    5: '漏针',
    6: '其他',
    8: '抛丝',
    9: '吊丝',
    10: '勾丝',
    11: '油污丝',
    12: '导电丝异常',
    13: '毛针',
    14: '其他',
    16: '破洞',
    17: '隐横路',
    18: '坏边右',
    21: '拼缝',
    22: '吊丝',
    23: '色丝（僵丝）',
    24: '盘头印',
    25: '轮胎印',
    26: '叉针',
    27: '钓伤',
    28: '漏针',
    29: '下边',
    33: '毛丝',
    34: '粘丝',
    35: '理边丝',
    37: '盘头毛刺',
    38: '勾丝',
    48: '理直条'
};

// 获取疵点类型名称
function getFlawTypeName(type) {
    return FLAW_TYPE_MAP[type] || `类型${type}`;
}

// 注册Chart.js插件
if (typeof Chart !== 'undefined' && typeof ChartDataLabels !== 'undefined') {
    Chart.register(ChartDataLabels);
} else {
    console.warn('Chart.js or ChartDataLabels not loaded');
}

// DOM元素
const machineGrid = document.getElementById('machineGrid');
const lastUpdateTime = document.getElementById('lastUpdateTime');
const autoRefreshStatus = document.getElementById('autoRefreshStatus');
const machineModal = document.getElementById('machineModal');
const modalTitle = document.getElementById('modalTitle');
const modalBody = document.getElementById('modalBody');
const closeModal = document.getElementById('closeModal');

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    loadData();
    startAutoRefresh();
    startRealTimeUpdate(); // 启动实时时间更新
    setupEventListeners();
}

// 加载数据
async function loadData() {
    try {
        console.log('开始加载数据...');
        
        // 同时获取机器数据和待翻品种计划数据
        const [machinesResponse, plansResponse] = await Promise.all([
            fetch('/api/monitor/machines'),
            fetch('/api/monitor/pending-plans')
        ]);

        console.log('API响应状态:', {
            machines: machinesResponse.status,
            plans: plansResponse.status
        });

        if (machinesResponse.ok && plansResponse.ok) {
            machineData = await machinesResponse.json();
            const plansResult = await plansResponse.json();
            pendingPlanData = convertPlansToArray(plansResult.plans);
            
            console.log('数据加载成功:', {
                machines: machineData.length,
                plans: pendingPlanData.length
            });
            
            renderMachineGrid();
            renderPendingPlanTable();
            updateLastUpdateTime();
        } else {
            console.error('Failed to load data:', {
                machines: machinesResponse.status,
                plans: plansResponse.status
            });
        }
    } catch (error) {
        console.error('Error loading data:', error);
    }
}

// 将计划数据转换为数组格式
function convertPlansToArray(plans) {
    const result = [];
    for (const machineNumber in plans) {
        const machinePlans = plans[machineNumber];
        for (const roundNumber in machinePlans) {
            result.push({
                machineNumber: parseInt(machineNumber),
                roundNumber: parseInt(roundNumber),
                planDetails: machinePlans[roundNumber]
            });
        }
    }
    return result;
}

// 渲染机器网格
function renderMachineGrid() {
    machineGrid.innerHTML = '';

    // 根据后端接口返回的数据动态渲染机器卡片
    machineData.forEach(machine => {
        const machineCard = createMachineCard(machine);
        machineGrid.appendChild(machineCard);
    });
    
    console.log(`渲染了 ${machineData.length} 台机器`);
}

// 创建机器卡片
function createMachineCard(machine) {
    const card = document.createElement('div');
    card.className = `machine-card ${machine.status.toLowerCase()}`;
    card.dataset.machineNumber = machine.machineNumber;
    
    const statusText = getStatusText(machine.status);
    const statusClass = machine.status.toLowerCase();
    
    // 格式化数据
    const formatFabricLength = (value) => {
        if (value === null || value === undefined || value === '') return '--';
        return parseFloat(value).toFixed(2);
    };
    
    const formatRemainingHours = (value) => {
        if (value === null || value === undefined || value === '') return '--';
        const numValue = parseFloat(value);
        if (isNaN(numValue)) return '--';
        return (numValue / 10).toFixed(1);
    };
    
    card.innerHTML = `
        <div class="machine-header ${statusClass}">
            <div class="machine-header-left">
                <span class="machine-mat-type">${machine.currentMatTypeName || '--'}</span>
            </div>
            <div class="machine-header-right">
                <span class="machine-number">${machine.machineNumber}#</span>
            </div>
        </div>
        <div class="machine-content">
            <div class="content-row">
                <div class="info-item">
                    <span class="info-label">布长</span>
                    <span class="info-value">${formatFabricLength(machine.fabricLength)}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">车速</span>
                    <span class="info-value">${machine.speed || '--'}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">工人</span>
                    <span class="info-value">${machine.operator || '--'}</span>
                </div>
            </div>
            <div class="content-row content-row-with-remaining">
                <div class="info-item">
                    <span class="info-label">L1:</span>
                    <span class="info-value">${machine.l1Pattern || '--'}</span>
                </div>
                <div class="info-item remaining-item">
                    <span class="info-label">剩余:</span>
                    <span class="info-value">${formatRemainingHours(machine.l1Remaining)}</span>
                    <span class="info-unit">小时</span>
                </div>
            </div>
            <div class="content-row content-row-with-remaining">
                <div class="info-item">
                    <span class="info-label">L2:</span>
                    <span class="info-value">${machine.l2Pattern || '--'}</span>
                </div>
                <div class="info-item remaining-item">
                    <span class="info-label">剩余:</span>
                    <span class="info-value">${formatRemainingHours(machine.l2Remaining)}</span>
                    <span class="info-unit">小时</span>
                </div>
            </div>
            <div class="content-row content-row-with-remaining">
                <div class="info-item">
                    <span class="info-label">L3:</span>
                    <span class="info-value">${machine.l3Pattern || '--'}</span>
                </div>
                <div class="info-item remaining-item">
                    <span class="info-label">剩余:</span>
                    <span class="info-value">${formatRemainingHours(machine.l3Remaining)}</span>
                    <span class="info-unit">小时</span>
                </div>
            </div>
            <div class="content-row content-row-with-remaining">
                <div class="info-item">
                    <span class="info-label">L4:</span>
                    <span class="info-value">${machine.l4Pattern || '--'}</span>
                </div>
                <div class="info-item remaining-item">
                    <span class="info-label">剩余:</span>
                    <span class="info-value">${formatRemainingHours(machine.l4Remaining)}</span>
                    <span class="info-unit">小时</span>
                </div>
            </div>
            <div class="content-row">
                <div class="info-item">
                    <span class="info-label">下轮计划</span>
                    <span class="info-value">${machine.nextPlan || '--'}</span>
                </div>
            </div>
        </div>
    `;
    
    // 添加点击事件
    card.addEventListener('click', () => {
        showMachineDetails(machine);
    });
    
    return card;
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'RUNNING': '运行中',
        'STOPPED': '质量停机',
        'MAINTENANCE': '维护中',
        'ERROR': '错误',
        'DISCONNECT': '失去连接'
    };
    return statusMap[status] || status;
}

// 渲染待翻品种计划表格
function renderPendingPlanTable() {
    // 清空所有表格
    for (let i = 1; i <= 5; i++) {
        const tableBody = document.getElementById(`planTableBody${i}`);
        if (tableBody) {
            tableBody.innerHTML = '';
        }
    }
    
    // 为每个表格组生成5行数据
    for (let tableIndex = 1; tableIndex <= 5; tableIndex++) {
        const tableBody = document.getElementById(`planTableBody${tableIndex}`);
        if (!tableBody) continue;
        
        // 计算该表格对应的机器范围
        const startMachine = (tableIndex - 1) * 5 + 1;
        const endMachine = Math.min(tableIndex * 5, 25);
        
        for (let machineNum = startMachine; machineNum <= endMachine; machineNum++) {
            const row = document.createElement('tr');
            
            // 机器号
            const machineCell = document.createElement('td');
            machineCell.textContent = `${machineNum}#`;
            row.appendChild(machineCell);
            
            // Round 1-3
            for (let round = 1; round <= 3; round++) {
                const cell = document.createElement('td');
                const plan = pendingPlanData.find(p => p.machineNumber === machineNum && p.roundNumber === round);
                cell.textContent = plan ? plan.planDetails : '';
                row.appendChild(cell);
            }
            
            tableBody.appendChild(row);
        }
    }
}

// 显示机器详情
async function showMachineDetails(machine) {
    try {
        // 显示加载状态
        modalBody.innerHTML = '<div style="text-align: center; color: #fff; padding: 20px;">加载中...</div>';
        machineModal.style.display = 'block';
        
        // 并行调用四个拆分后的API接口
        const [basicResponse, chartsResponse, defectsResponse, guideBarsResponse] = await Promise.all([
            fetch(`/api/monitor/machines/${machine.machineNumber}/basic`),
            fetch(`/api/monitor/machines/${machine.machineNumber}/charts`),
            fetch(`/api/monitor/machines/${machine.machineNumber}/defects`),
            fetch(`/api/monitor/machines/${machine.machineNumber}/guide-bars`)
        ]);
        
        // 检查所有响应是否成功
        if (!basicResponse.ok || !chartsResponse.ok || !defectsResponse.ok || !guideBarsResponse.ok) {
            throw new Error('获取机器详情失败');
        }
        
        // 解析所有响应数据
        const [basicData, chartsData, defectsData, guideBarsData] = await Promise.all([
            basicResponse.json(),
            chartsResponse.json(),
            defectsResponse.json(),
            guideBarsResponse.json()
        ]);
        
        // 更新模态框标题和当前车速
        document.getElementById('modalMachineNumber').textContent = `${basicData.machineNumber}#`;
        document.getElementById('modalCurrentSpeed').textContent = basicData.currentSpeed || '--';
        
        // 格式化数值函数
        const formatNumber = (value) => {
            if (value === null || value === undefined || value === '') return '--';
            const numValue = parseFloat(value);
            if (isNaN(numValue)) return '--';
            return numValue.toFixed(2);
        };
        
        // 构建HTML内容
        const details = `
            <div class="modal-detail-layout">
                <!-- 第一行：机器/订单详情表格、工艺/疵点详情表格和饼图 -->
                <div class="modal-top-row">
                    <!-- 机器/订单详情表格 -->
                    <div class="modal-table-section compact">
                        <h4>机器/订单详情</h4>
                        <table class="modal-detail-table compact-table">
                            <tr>
                                <td class="table-label">物料类型</td>
                                <td class="table-value">${basicData.materialType}</td>
                            </tr>
                            <tr>
                                <td class="table-label">订单编号</td>
                                <td class="table-value">${basicData.orderNumber}</td>
                            </tr>
                            <tr>
                                <td class="table-label">订单数量(米)</td>
                                <td class="table-value">${formatNumber(basicData.orderQuantity)}</td>
                            </tr>
                            <tr>
                                <td class="table-label">已完成数量(米)</td>
                                <td class="table-value">${formatNumber(basicData.completedQuantity)}</td>
                            </tr>
                            <tr>
                                <td class="table-label">当前米数(米)</td>
                                <td class="table-value">${formatNumber(basicData.currentMeters)}</td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- 工艺/疵点详情表格 -->
                    <div class="modal-table-section compact">
                        <h4>工艺/疵点详情</h4>
                        <table class="modal-detail-table compact-table">
                            <tr>
                                <td class="table-label">工艺卡</td>
                                <td class="table-value">${basicData.processCard}</td>
                            </tr>
                            <tr>
                                <td class="table-label">生产员工</td>
                                <td class="table-value">${basicData.productionEmployee}</td>
                            </tr>
                            <tr>
                                <td class="table-label">停车疵点数</td>
                                <td class="table-value">${defectsData.parkingDefectCount}</td>
                            </tr>
                            <tr>
                                <td class="table-label">非停车疵点数</td>
                                <td class="table-value">${defectsData.nonParkingDefectCount}</td>
                            </tr>
                            <tr>
                                <td class="table-label">疵点总数</td>
                                <td class="table-value">${defectsData.totalDefectCount}</td>
                            </tr>
                        </table>
                    </div>
                    
                    <!-- 订单完成进度饼图 -->
                    <div class="chart-section">
                        <h4>订单完成进度</h4>
                        <div class="chart-container">
                            <canvas id="completionChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <!-- 第二行：梳栉/盘头详情表格 -->
                <div class="modal-bottom-row">
                    <div class="modal-table-section full-width">
                        <h4>梳栉/盘头详情</h4>
                        <table class="modal-detail-table">
                            <tr>
                                <td class="table-label" style="width: 25%;">梳栉号</td>
                                <td class="table-label" style="width: 25%;">机上盘头号</td>
                                <td class="table-label" style="width: 50%;">待上机盘头号</td>
                            </tr>
                            ${guideBarsData.map(detail => `
                                <tr>
                                    <td class="table-value">${detail.guideBarNumber}</td>
                                    <td class="table-value">${detail.machineBobbinNumber}</td>
                                    <td class="table-value">${detail.pendingBobbinNumber || '待分配'}</td>
                                </tr>
                            `).join('')}
                        </table>
                    </div>
                </div>
                
                <!-- 第三行：故障分布图和时间图 -->
                <div class="modal-charts-row">
                    <!-- 故障分布图 -->
                    <div class="chart-section">
                        <h4>故障分布图</h4>
                        <div class="chart-container">
                            <canvas id="scatterChart"></canvas>
                        </div>
                    </div>
                    
                    <!-- 时间图 -->
                    <div class="chart-section">
                        <h4>时间图</h4>
                        <div class="chart-container">
                            <canvas id="timelineChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        modalBody.innerHTML = details;
        
        // 渲染图表
        renderChartsFromData(chartsData);
        
    } catch (error) {
        console.error('获取机器详情失败:', error);
        modalBody.innerHTML = '<div style="text-align: center; color: #ff6b6b; padding: 20px;">加载失败，请重试</div>';
    }
}

// 渲染图表
function renderCharts(machine) {
    // 订单完成进度饼图
    const completionCtx = document.getElementById('completionChart').getContext('2d');
    new Chart(completionCtx, {
        type: 'pie',
        data: {
            labels: ['已完成数量(米)', '订单数量(米)'],
            datasets: [{
                data: [13527, 11473], // 已完成13527米，剩余11473米
                backgroundColor: ['#2196F3', '#FF9800'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#fff',
                        font: {
                            size: 11
                        },
                        padding: 8
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(0);
                            return `${label}: ${value}米 (${percentage}%)`;
                        }
                    }
                },
                datalabels: {
                    color: '#fff',
                    font: {
                        weight: 'bold',
                        size: 12
                    },
                    formatter: function(value, context) {
                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                        const percentage = ((value / total) * 100).toFixed(0);
                        return percentage + '%';
                    }
                }
            }
        }
    });
    
    // 故障分布散点图
    const scatterCtx = document.getElementById('scatterChart').getContext('2d');
    new Chart(scatterCtx, {
        type: 'scatter',
        data: {
            datasets: [
                {
                    label: '无故障',
                    data: [
                        {x: 50, y: 0}, {x: 100, y: 0}, {x: 150, y: 0}, {x: 200, y: 0}, {x: 250, y: 0}
                    ],
                    backgroundColor: '#2196F3',
                    pointRadius: 6
                },
                {
                    label: 'GB1',
                    data: [
                        {x: 75, y: 1}, {x: 125, y: 1}, {x: 175, y: 1}
                    ],
                    backgroundColor: '#87CEEB',
                    pointRadius: 6
                },
                {
                    label: getFlawTypeName(0), // 停车位
                    data: [
                        {x: 30, y: 2}, {x: 80, y: 2}, {x: 130, y: 2}, {x: 180, y: 2}, {x: 230, y: 2}
                    ],
                    backgroundColor: '#000',
                    pointRadius: 6
                },
                {
                    label: getFlawTypeName(2), // 断头
                    data: [
                        {x: 45, y: 3}, {x: 95, y: 3}, {x: 145, y: 3}, {x: 195, y: 3}, {x: 245, y: 3}
                    ],
                    backgroundColor: '#F44336',
                    pointRadius: 6
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#fff',
                        font: {
                            size: 12,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        }
                    }
                },
                datalabels: {
                    display: true, // 显示数据点上的数值标签
                    color: '#fff',
                    font: {
                        size: 10,
                        weight: 'bold',
                        family: 'Microsoft YaHei, Arial, sans-serif'
                    },
                    anchor: 'bottom',
                    align: 'center',
                    offset: 8,
                    formatter: function(value, context) {
                        // 显示故障类型名称
                        return context.dataset.label;
                    }
                },
                tooltip: {
                    enabled: true,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 1,
                    callbacks: {
                        title: function(context) {
                            return `位置: ${context[0].parsed.x.toFixed(1)}`;
                        },
                        label: function(context) {
                            return `故障类型: ${context.dataset.label}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    type: 'linear',
                    position: 'bottom',
                    min: 0,
                    max: 292.5,
                    display: true, // 显示X轴
                    title: {
                        display: true,
                        text: '位置',
                        color: '#fff',
                        font: {
                            size: 12,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        }
                    },
                    ticks: {
                        color: '#fff',
                        font: {
                            size: 11,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        },
                        display: true, // 显示X轴刻度值
                        callback: function(value) {
                            return value.toFixed(1);
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)' // 显示网格线
                    }
                },
                y: {
                    type: 'linear',
                    position: 'left',
                    min: -0.5,
                    max: 3.5, // 根据实际数据动态调整，这里使用固定值因为数据是硬编码的
                    display: true, // 显示Y轴
                    title: {
                        display: true,
                        text: '故障类型',
                        color: '#fff',
                        font: {
                            size: 12,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        }
                    },
                    ticks: {
                        color: '#fff',
                        font: {
                            size: 11,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        },
                        display: true, // 显示Y轴刻度值
                        callback: function(value) {
                            const labels = ['', '无故障', '停车位', '断头'];
                            return labels[value] || '';
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)', // 显示网格线
                        drawTicks: false
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'nearest'
            }
        }
    });
    
    // 时间图（水平条形图）
    const timelineCtx = document.getElementById('timelineChart').getContext('2d');
    new Chart(timelineCtx, {
        type: 'bar',
        data: {
            labels: ['工作时间'],
            datasets: [
                {
                    label: '徐丽娜',
                    data: [22], // 22小时
                    backgroundColor: '#FF00FF',
                    borderColor: '#FF00FF',
                    borderWidth: 1
                },
                {
                    label: '周仕奎',
                    data: [2], // 2小时
                    backgroundColor: '#FFA500',
                    borderColor: '#FFA500',
                    borderWidth: 1
                }
            ]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#fff',
                        font: {
                            size: 12
                        }
                    }
                }
            },
            scales: {
                x: {
                    stacked: true,
                    min: 0,
                    max: 24,
                    ticks: {
                        color: '#fff',
                        callback: function(value) {
                            return value + ':00';
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                },
                y: {
                    stacked: true,
                    ticks: {
                        color: '#fff'
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                }
            }
        }
    });
}

// 根据后端数据渲染图表
function renderChartsFromData(chartData) {
    // 订单完成进度饼图
    const completionCtx = document.getElementById('completionChart').getContext('2d');
    new Chart(completionCtx, {
        type: 'pie',
        data: {
            labels: chartData.completionData.map(item => item.label),
            datasets: [{
                data: chartData.completionData.map(item => item.value),
                backgroundColor: chartData.completionData.map(item => item.color),
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#fff',
                        font: {
                            size: 11
                        },
                        padding: 8
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(0);
                            return `${label}: ${value}米 (${percentage}%)`;
                        }
                    }
                },
                datalabels: {
                    color: '#fff',
                    font: {
                        weight: 'bold',
                        size: 12
                    },
                    formatter: function(value, context) {
                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                        const percentage = ((value / total) * 100).toFixed(0);
                        return percentage + '%';
                    }
                }
            }
        }
    });
    
    // 故障分布散点图
    const scatterCtx = document.getElementById('scatterChart').getContext('2d');
    
    // 按类型分组故障数据
    const faultGroups = {};
    chartData.faultData.forEach(fault => {
        if (!faultGroups[fault.type]) {
            faultGroups[fault.type] = [];
        }
        faultGroups[fault.type].push({x: fault.x, y: fault.y});
    });
    
    // 计算Y轴的最大值，根据实际数据动态调整
    const yValues = chartData.faultData.map(fault => fault.y);
    const maxY = yValues.length > 0 ? Math.max(...yValues) : 3.5;
    
    const scatterDatasets = Object.keys(faultGroups).map(type => ({
        label: type, // 直接使用类型名称，因为后端返回的是中文名称
        data: faultGroups[type],
        backgroundColor: chartData.faultData.find(f => f.type === type).color,
        pointRadius: 6
    }));
    
    new Chart(scatterCtx, {
        type: 'scatter',
        data: {
            datasets: scatterDatasets
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#fff',
                        font: {
                            size: 12,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        }
                    }
                },
                datalabels: {
                    display: true, // 显示数据点上的数值标签
                    color: '#fff',
                    font: {
                        size: 10,
                        weight: 'bold',
                        family: 'Microsoft YaHei, Arial, sans-serif'
                    },
                    anchor: 'bottom',
                    align: 'center',
                    offset: 8,
                    formatter: function(value, context) {
                        // 显示故障类型名称
                        return context.dataset.label;
                    }
                },
                tooltip: {
                    enabled: true,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 1,
                    callbacks: {
                        title: function(context) {
                            return `位置: ${context[0].parsed.x.toFixed(1)}`;
                        },
                        label: function(context) {
                            return `故障类型: ${context.dataset.label}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    type: 'linear',
                    position: 'bottom',
                    min: 0,
                    max: 292.5,
                    display: true, // 显示X轴
                    title: {
                        display: true,
                        text: '位置',
                        color: '#fff',
                        font: {
                            size: 12,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        }
                    },
                    ticks: {
                        color: '#fff',
                        font: {
                            size: 11,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        },
                        display: true, // 显示X轴刻度值
                        callback: function(value) {
                            return value.toFixed(1);
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)' // 显示网格线
                    }
                },
                y: {
                    type: 'linear',
                    position: 'left',
                    min: -0.5,
                    max: maxY + 0.5,
                    display: true, // 显示Y轴
                    title: {
                        display: true,
                        text: '故障类型',
                        color: '#fff',
                        font: {
                            size: 12,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        }
                    },
                    ticks: {
                        color: '#fff',
                        font: {
                            size: 11,
                            family: 'Microsoft YaHei, Arial, sans-serif'
                        },
                        display: true, // 显示Y轴刻度值
                        callback: function(value) {
                            // 根据实际故障类型动态生成标签
                            const faultTypes = [...new Set(chartData.faultData.map(f => f.type))];
                            const labels = ['', ...faultTypes];
                            return labels[value] || '';
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)', // 显示网格线
                        drawTicks: false
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'nearest'
            }
        }
    });
    
    // 时间图（水平条形图）
    const timelineCtx = document.getElementById('timelineChart').getContext('2d');
    
    // 计算时间范围
    let minTime = 0;
    let maxTime = 24;
    
    if (chartData.timeData && chartData.timeData.length > 0) {
        // 从所有时间数据中找出最早和最晚的时间
        const allTimes = [];
        chartData.timeData.forEach(time => {
            if (time.startTime) {
                const startHour = parseInt(time.startTime.split(':')[0]);
                allTimes.push(startHour);
            }
            if (time.endTime) {
                const endHour = parseInt(time.endTime.split(':')[0]);
                allTimes.push(endHour);
            }
        });
        
        if (allTimes.length > 0) {
            minTime = Math.max(0, Math.min(...allTimes) - 1); // 提前1小时
            maxTime = Math.min(24, Math.max(...allTimes) + 1); // 延后1小时
        }
    }
    
    new Chart(timelineCtx, {
        type: 'bar',
        data: {
            labels: ['工作时间'],
            datasets: chartData.timeData.map(time => ({
                label: `${time.employee} (${time.startTime || '--'}~${time.endTime || '--'})`,
                data: [time.hours],
                backgroundColor: time.color,
                borderColor: time.color,
                borderWidth: 1
            }))
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#fff',
                        font: {
                            size: 12
                        }
                    }
                }
            },
            scales: {
                x: {
                    stacked: true,
                    min: minTime,
                    max: maxTime,
                    ticks: {
                        color: '#fff',
                        callback: function(value) {
                            return value + ':00';
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                },
                y: {
                    stacked: true,
                    ticks: {
                        color: '#fff'
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                }
            }
        }
    });
}

// 更新最后更新时间
function updateLastUpdateTime() {
    const now = new Date();
    // 使用更详细的时间格式，包含秒
    const timeString = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
    lastUpdateTime.textContent = timeString;
}

// 开始实时时间更新
function startRealTimeUpdate() {
    console.log('开始实时时间更新...');
    // 立即更新一次
    updateLastUpdateTime();
    // 每秒更新一次时间
    const timeInterval = setInterval(() => {
        updateLastUpdateTime();
    }, 1000);
    
    // 保存定时器ID，以便后续清理
    window.timeUpdateInterval = timeInterval;
}

// 开始自动刷新
function startAutoRefresh() {
    refreshInterval = setInterval(() => {
        loadData();
    }, REFRESH_INTERVAL); // 每30秒刷新一次
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
    
    // 同时停止时间更新
    if (window.timeUpdateInterval) {
        clearInterval(window.timeUpdateInterval);
        window.timeUpdateInterval = null;
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 关闭模态框
    closeModal.addEventListener('click', () => {
        machineModal.style.display = 'none';
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === machineModal) {
            machineModal.style.display = 'none';
        }
    });
}

// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
}); 